package apy.codecase.rv;

import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import java.util.ArrayList;

import apy.codecase.R;
import apy.codecase.base.BaseActivity;


/**
 * RecyclerView的基类
 */
public abstract class BaseListActivity<K,T> extends BaseActivity<K,T> implements PullRecycler.OnRecyclerRefreshListener {
    protected BaseListAdapter adapter;
    protected ArrayList<T> mDataList;
    protected PullRecycler recycler;

    @Override
    protected int getViewId() {
        return R.layout.activity_base_list;
    }

    @Override
    protected void initData() {
        recycler = (PullRecycler) findViewById(R.id.pullRecycler);
        setUpAdapter();
        recycler.setOnRefreshListener(this);
        recycler.setLayoutManager(getLayoutManager());
//        recycler.addItemDecoration(getItemDecoration());
        recycler.setAdapter(adapter);
    }
    protected void setUpAdapter() {
        adapter = new ListAdapter();
    }

    protected ILayoutManager getLayoutManager() {
        return new MyLinearLayoutManager(getApplicationContext());
    }

    protected RecyclerView.ItemDecoration getItemDecoration() {
        return new DividerItemDecoration(getApplicationContext(), R.drawable.list_divider);
    }

    public class ListAdapter extends BaseListAdapter {

        @Override
        protected BaseViewHolder onCreateNormalViewHolder(ViewGroup parent, int viewType) {
            return getViewHolder(parent, viewType);
        }

        @Override
        protected int getDataCount() {
            int itemType = getItemType(0);
            if(itemType == 3){
                return mDataList != null ? mDataList.size()+2: 0;
            }else if(itemType!=0){
                return mDataList != null ? mDataList.size()+1: 0;
            }
            return mDataList != null ? mDataList.size(): 0;
        }

        @Override
        protected int getDataViewType(int position) {
            return getItemType(position);
        }

        @Override
        public boolean isSectionHeader(int position) {
            return BaseListActivity.this.isSectionHeader(position);
        }
    }

    @Override
    public void afterLoadDataAsObject(Object t) {
        super.afterLoadDataAsObject(t);
        if(mDataList==null){
            mDataList = new ArrayList<>();
        }
    }

    @Override
    public void afterLoadData(K t, T t2) {
        super.afterLoadData(t, t2);
        if(mDataList==null){
            mDataList = new ArrayList<>();
        }
    }

    protected boolean isSectionHeader(int position) {
        return false;
    }

    protected int getItemType(int position) {
        return 0;
    }

    protected abstract BaseViewHolder getViewHolder(ViewGroup parent, int viewType);

}
